package com.cus.tom.transfer.frag;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.provider.Telephony;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.cus.tom.transfer.BuildConfig;
import com.cus.tom.transfer.adapter.InfoAdapter;
import com.cus.tom.transfer.bean.FileType;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.sms.SmsTools;
import com.cus.tom.transfer.utils.Read;
import com.cus.tom.transfer.utils.ToastUtil;
import com.cus.tom.transfer.utils.Write;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;
import com.plata.base.aclr.utils.SPHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class RecordInfoFragment extends RecordImgFragment {
    public RecordInfoFragment(int type) {
        super(type);
    }

    @Override
    protected void setAdapter() {
        binding.tip.setVisibility(View.GONE);
        binding.export.setVisibility(View.GONE);
        binding.rvAlbum.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new InfoAdapter(this, type);
        binding.rvAlbum.setAdapter(adapter);
    }

    @Override
    protected List<MediaData> getMediaData() {
        if (!XXPermissions.isGranted(getActivity(), Permission.MANAGE_EXTERNAL_STORAGE)) {
            return Collections.emptyList();
        }

        List<MediaData> list = new ArrayList<>();
        list.addAll(dao.getAllByType(FileType.CONTRACT));
        list.addAll(dao.getAllByType(FileType.SMS));
        list.addAll(dao.getAllByType(FileType.CALL));
        Collections.sort(list, new Comparator<MediaData>() {
            @Override
            public int compare(MediaData o1, MediaData o2) {
                if (o1.getAddTime() > o2.getAddTime()) {
                    return -1;
                } else if (o1.getAddTime() < o2.getAddTime()) {
                    return 1;
                }
                return 0;
            }
        });
        return list;
    }

    MediaData smsData;

    public void checkPermission(MediaData data, String... permission) {
        Read.toSetting(getActivity(), new Runnable() {
            @Override
            public void run() {
                if (data.getType() == FileType.CONTRACT.getCode()) {
                    ((InfoAdapter) adapter).updateRight(0, true);
                    LoadingDlg dlg = new LoadingDlg();
                    dlg.setCancelable(false);
                    dlg.show(getChildFragmentManager(), "");
                    TaskEngine.getInstance().submit(new SilentTask("") {
                        @Override
                        public void runInBackground() throws Exception {
                            new Write().addContract(data, dlg);
                            h.post(() -> {
                                dlg.dismiss();
                                ToastUtil.showShortToast(getActivity(), "导入联系人完成");
                            });
                        }

                        @Override
                        public long getTimeout() {
                            return 0;
                        }
                    });
                } else if (data.getType() == FileType.SMS.getCode()) {
                    if (!isDefaultSms()) {
                        TipDlg dlg = new TipDlg();
                        dlg.setCancelable(false);
                        dlg.setMsg("需要你在接下来的对话框中选择“确定”（或“允许”、“是”），以确保在新手机上写入短信，写入完毕后将还原").setOk("确定");
                        dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                            @Override
                            public void onDismiss(boolean isOk, Object value) {
                                if (isOk) {
                                    smsData = data;
                                    SmsTools.getInstance(getActivity()).setDefaultSms(RecordInfoFragment.this, 50, BuildConfig.APPLICATION_ID);
                                } else {
                                    smsData = null;
                                }
                            }
                        });
                        dlg.show(getChildFragmentManager(), "");
                        return;
                    }
                    doImportSms(data);
                } else if (data.getType() == FileType.CALL.getCode()) {
                    ((InfoAdapter) adapter).updateRight(2, true);
                    LoadingDlg dlg = new LoadingDlg().setMsg("导入通话记录...");
                    dlg.setCancelable(false);
                    dlg.show(getChildFragmentManager(), "");
                    TaskEngine.getInstance().submit(new SilentTask("") {
                        @Override
                        public void runInBackground() throws Exception {
                            new Write().addPhoneCall(data, dlg);
                            h.post(() -> {
                                dlg.dismiss();
                                ToastUtil.showShortToast(getActivity(), "导入通话记录完成");
                            });
                        }

                        @Override
                        public long getTimeout() {
                            return 0;
                        }
                    });

                }
            }
        }, false, permission);
    }

    private void doImportSms(MediaData data) {
        ((InfoAdapter) adapter).updateRight(1, true);
        LoadingDlg dlg = new LoadingDlg();
        dlg.setCancelable(false);
        dlg.show(getChildFragmentManager(), "");
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                new Write().addSms(data, dlg);
                h.post(() -> {
                    dlg.dismiss();
                    smsData = null;
                    TipDlg dlg = new TipDlg();
                    dlg.setCancelable(false);
                    dlg.setMsg("短信已经写入完毕，为了正常使用短信功能，请恢复之前的默认短信授权").setOk("确定");
                    dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                        @Override
                        public void onDismiss(boolean isOk, Object value) {
                            if (isOk) {
                                SmsTools.resetSms(RecordInfoFragment.this, 50);
                            }
                        }
                    });
                    dlg.show(getChildFragmentManager(), "");
                });
            }

            @Override
            public long getTimeout() {
                return 0;
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 50 && resultCode == RESULT_OK && smsData != null) {
            doImportSms(smsData);
        }
    }

    private boolean isDefaultSms() {
        String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(getActivity());//获取手机当前设置的默认短信应用的包名
        boolean bo = BuildConfig.APPLICATION_ID.equals(defaultSmsApp);
        if (!bo) {
            SPHelper.getInstance(getActivity()).putString("oldSms", defaultSmsApp).commit();
        }
        return bo;
    }
}
